<?php
/**
 * Created by PhpStorm.
 * User: chenx
 * Date: 18-3-16
 * Time: 下午6:32
 */

namespace shopend\controllers;


use common\models\Active;
use common\models\ActiveAttr;
use common\models\Express;
use common\models\Goods;
use common\models\Group;
use common\models\Order;
use common\models\Shop;
use common\service\CommonService;
use common\service\GlobalUrlService;
use common\service\ConstantService;
use common\service\LogisticsService;
use common\models\User;
use common\service\GoodsService;
use common\service\RedisServer;
use common\service\WechatService;

class OrderController extends BaseController
{
    /**
     * 列表
     */
    public function actionIndex(){
        if($this->isGet() && $this->isAjax()){
            $query = Order::find();
            $addressee_name = $this->get('addressee_name','');
            $search_type = $this->get('search_type','');
            $query->andWhere(['shop_id'=>$this->shop['id']]);
            if(!empty($addressee_name) && !empty($search_type)){
                if($this->get('search_type') == 1){
                    $query->andWhere(['like','addressee_phone',$addressee_name]);
                } else {
                    $query->andWhere(['like','addressee_name',$addressee_name]);
                }
            }

            if(!empty($this->get('order_status'))){
                $query->andWhere(['order_status'=>$this->get('order_status')-1]);
            }
            if(!empty($this->get('start_time'))){
                $query->andWhere(['>=','created_time',strtotime($this->get('start_time'))]);
            }
            if(!empty($this->get('end_time'))){
                $query->andWhere(['<=','created_time',strtotime($this->get('end_time'))]);
            }
            $p = intval( $this->get('page',1) );
            $p = ( $p > 0 )? $p : 1;
            $total_count = $query->count();

            $offset = ($p - 1) * $this->get('limit',10);
            $orders = $query->asArray()
                ->offset($offset)
                ->limit($this->get('limit',10))
                ->orderBy(['created_time' => SORT_DESC,'id'=>SORT_DESC])
                ->asArray()
                ->all();
            $new_goods_attr = [];
//            if(!empty($orders)){
//
//                $goods_attr_ids = array_column($orders,'goods_attr_id');
//
//                //获取sku
//                $new_goods_attr = GoodsService::getCurrentArrt($goods_attr_ids);
//            }
//
//            foreach ($orders as &$item ){
//                $item['sku'] = '';
//                if(isset($new_goods_attr[$item['goods_attr_id']]) && !empty($new_goods_attr[$item['goods_attr_id']])){
//                    $item['sku'] = $new_goods_attr[$item['goods_attr_id']];
//                }
//            }
            return $this->renderJson($orders,$total_count,ConstantService::$response_tab_success);
        }
        $status = 0;
        if(!empty($this->get('order_status'))){
            $status = $this->get('order_status');
        }
        return $this->render('index',['status'=>$status]);
    }

    /**
     * 修改订单详情
     */
    public function actionUpdateOrder(){
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
            if(empty($data['id'])){
                return $this->renderJson([],'id错误',ConstantService::$response_fail);
            }
            if(empty($data['province'])){
                return $this->renderJson([],'省级地区不能为空',ConstantService::$response_fail);
            }
            if(empty($data['city'])){
                return $this->renderJson([],'市级地区不能为空',ConstantService::$response_fail);
            }
            if(empty($data['county'])){
                return $this->renderJson([],'县级地区不能为空',ConstantService::$response_fail);
            }
            if(empty($data['address'])){
                return $this->renderJson([],'详细地址不能为空',ConstantService::$response_fail);
            }
            if(empty($data['addressee_name'])){
                return $this->renderJson([],'收件人姓名不能为空',ConstantService::$response_fail);
            }
            if(!preg_match('/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$/',$data['addressee_phone']))
            {
                return $this->renderJson([],'请输入正确的手机号',ConstantService::$response_fail);
            }
            $order = Order::findOne(['id'=>$data['id']]);
            $order->setAttributes($data);
            if($order->save()){
                return $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
            return $this->renderJson($order->getErrors(),'修改失败',ConstantService::$response_fail);
        }
        $id = $this->get('id');
        $data = $this->_getinfo($id);

        return $this->render('update-order',$data);
    }

    /**
     * 查看订单详情
     */
    public function actionGetInfo(){
        $id = $this->get('id');
        $data = Order::find()->where(['id'=>$id])->asArray()->one();
        $vdata  = GoodsService::getCurrentArrt([$data['goods_attr_id']]);
        $data['sku'] = !empty($vdata[$data['goods_attr_id']]) ? $vdata[$data['goods_attr_id']] :'';

        $shop = Shop::findOne(['id'=>$data['shop_id']]);
        $data['shop_name'] = $shop['shop_name'];

        $activity = Active::findOne(['id'=>$data['active_id']]);
        $data['activity_name'] = $activity['active_name'];

        $goods = Goods::findOne(['id'=>$data['goods_id']]);
//        $data['type'] = ($goods['type'] == 1)?'实体商品':'虚拟商品';
        //这里缺参团的人头像
        $users = [];

        if($data['group_id']){
            $orders = Order::find()
                ->select(['user_id'])
                ->where(['group_id' => $data['group_id']])
                ->asArray()
                ->all();

            $user_id = array_column($orders, 'user_id');
            $users = User::find()
                ->select(['avatarurl'])
                ->where(['id' => $user_id])
                ->asArray()
                ->all();
            foreach ($users as &$user) {
                $user['avatarurl'] = GlobalUrlService::buildCdnUrl($user['avatarurl']);
            }
        } else {
            //单独购买
            $user = User::find()
                ->select(['avatarurl'])
                ->where(['id'=>$data['user_id']])
                ->asArray()
                ->one();
            $user['avatarurl'] = GlobalUrlService::buildCdnUrl($user['avatarurl']);
            $users[0] = $user;
        }

        return $this->render('get-info',['data'=>$data,'users'=>$users]);
    }

    /**
     * 查看单个
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public function _getinfo($id){
        $shop_id = $this->shop['id'];
        $data = Order::find()->where(['id'=>$id,'shop_id'=>$shop_id])->asArray()->one();
        if(empty($data)){
            return [];
        }


        $vdata  = GoodsService::getCurrentArrt([$data['goods_attr_id']]);
        $data['sku'] = !empty($vdata[$data['goods_attr_id']]) ? $vdata[$data['goods_attr_id']] :'';

        $shop = Shop::findOne(['id'=>$data['shop_id']]);
        $data['shop_name'] = $shop['shop_name'];

        $activity = Active::findOne(['id'=>$data['active_id']]);
        $data['activity_name'] = $activity['active_name'];

        $goods = goods::findOne(['id'=>$data['goods_id']]);
        $data['type'] = ($goods['type'] == 1)?'实体商品':'虚拟商品';
        //参团人头像
        $users = [];
        if($data['pay_status'] == 1){
            if($data['group_id']){
                $orders = Order::find()
                    ->select(['user_id'])
                    ->where(['group_id' => $data['group_id']])
                    ->asArray()
                    ->all();

                $user_id = array_column($orders, 'user_id');
                $users = User::find()
                    ->select(['avatarurl'])
                    ->where(['id' => $user_id])
                    ->asArray()
                    ->all();
                foreach ($users as &$user) {
                    $user['avatarurl'] = GlobalUrlService::buildCdnUrl($user['avatarurl']);
                }
            } else {
                //单独购买
                $user = User::find()
                    ->select(['avatarurl'])
                    ->where(['id'=>$data['user_id']])
                    ->asArray()
                    ->one();
                $user['avatarurl'] = GlobalUrlService::buildCdnUrl($user['avatarurl']);
                $users[0] = $user;
            }
        }
        return ['data'=>$data,'users'=>$users];
    }

    /**
     * 修改发货状态和订单号
     */
    public function actionSendGoods(){
        if($this->isAjax() && $this->isPost()){
            $id = $this->post('id');
            $transport_no = $this->post('transport_two');
            $express = $this->post('express');
            $status = ConstantService::$order_status['WAIT_RECEIPT'];
            $expdata = Express::find()->where(['code'=>$express])->asArray()->one();
            if(empty($transport_no)){
                return $this->renderJson([],'运单号不能为空',ConstantService::$response_fail);
            }
            if(empty($expdata)){
                return $this->renderJson([],'请选择快递公司',ConstantService::$response_fail);
            }
            $order = Order::findOne(['id'=>$id]);
            if(!$order){
                return $this->renderJson([],'该订单不存在',ConstantService::$response_fail);
            }
            $order->setAttributes(['id'=>$id,'order_status'=>$status,'transport_no'=>$transport_no,'express'=>$expdata['express_name'],'express_code'=>$express,'send_time'=>time()]);
            if($order->save()){
                return $this->renderJson([],'操作成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'操作失败',ConstantService::$response_fail);

        }
        return $this->renderJson([],'请求错误',ConstantService::$response_fail);
    }

    /**
     * 查看SKU
     */
    public function actionGetGoogsattr(){
        $id = $this->post('attr_id');
        $list = GoodsService::GetAttrlist($id);
        return $this->renderJson($list,'',ConstantService::$response_success);
    }

    /**
     * 继续发货
     */
    public function actionDeliverGoods(){
        $id = $this->post('id');
        $transport_on = $this->post('transport_two');
        $expval = $this->post('express');
        $expdata = Express::find()->where(['code'=>$expval])->asArray()->one();
        if(empty($transport_on)){
            return $this->renderJson([],'请填写订单号',ConstantService::$response_fail);
        }
        if(empty($expdata)){
            return $this->renderJson([],'请选择快递公司',ConstantService::$response_fail);
        }
        $order = Order::findOne(['id'=>$id]);
        $order->refund_time = '';
        $order->order_status = ConstantService::$order_status['WAIT_RECEIPT'];
        $order->transport_no = $transport_on;
        $order->express = $expdata['express_name'];
        $order->express_code = $expval;
        $order->send_time = time();
        if($order->save()){
            return $this->renderJson([],'操作成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'发货失败',ConstantService::$response_fail);
    }

    /**
     * 退款
     */
    public function actionRefundGoods(){
        $id = $this->post('id');
        $order = Order::findOne(['id'=>$id]);
        $out_refund_no = CommonService::createOrderNo();
        //新增一个退款订单号
        $order->out_refund_no = $out_refund_no;
        $appid= \Yii::$app->params['wechat']['appid'];
        $mchid= \Yii::$app->params['wechat']['mchid'];
        $wechat_key= \Yii::$app->params['wechat']['key'];
        $total_fee = $order['order_money']*100;
        $refund_fee = $order['order_money']*100;
        $result = WechatService::applyRefund($appid,$mchid,$order['serial_no'],$out_refund_no,$total_fee,$refund_fee,$wechat_key);

        if($result === false || $result['result_code'] =='FAIL'){
            return $this->renderJson([],'退款失败',ConstantService::$response_fail);
        }

        //将库存加回去  将成团表数量减去
        $Activity_attr = ActiveAttr::findOne(['id'=>$order['goods_attr_id']]);
        $inventory = $Activity_attr['inventory'];
        $Activity_attr->inventory = $inventory+$order['goods_num'];

        //加入redis存储库存
        $key = ConstantService::$redis_key.$order['goods_attr_id'];
        //判断key是否存在
        $redis = RedisServer::initialization();
        $inventory_redis = $redis->getRedis($key);
        if($inventory_redis){
            //有redis
            $inventory_redis = $inventory_redis+$order['goods_num'];
            $redis->addRedis($key,$inventory_redis);

        }
        if($order['order_type'] == 1){
            //团购
            $group = Group::findOne(['id'=>$order['group_id']]);
            $group->current_group_num = $group['current_group_num'] - 1;
            $group->save();
        }

        if($Activity_attr->save()){
            $order->order_status = ConstantService::$order_status['CLOSED'];
            if($order->save()){
                return $this->renderJson([],'退款成功',ConstantService::$response_success);
            }

        }
        return $this->renderJson([],'退款失败',ConstantService::$response_fail);
    }

    /**
     * 快递
     */
    public function actionGetExpress(){
        $data = Express::find()->asArray()->all();
        return $this->renderJson($data,'',ConstantService::$response_success);
    }
}